package com.stormrage.edu.serv.edu.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.stormrage.constants.ErrCons;
import com.stormrage.edu.dao.edu.EduVideoDao;
import com.stormrage.edu.dao.edu.view.EduChapterVideoDao;
import com.stormrage.edu.serv.edu.EduVideoServ;
import com.stormrage.entity.edu.EduVideo;
import com.stormrage.entity.edu.rep.EduVideoRep;
import com.stormrage.entity.edu.req.EduVideoReq;
import com.stormrage.entity.rep.ListRep;
import com.stormragetech.core.entity.UploadVideoRep;
import com.stormragetech.core.exception.StormrageTechException;
import com.stormragetech.core.util.FileUtil;

/**
 * @Title: EduVideoServImpl.java
 * @Package com.stormrage.edu.serv.edu.impl
 * @Description: 课件 Service
 * @author www.stormragetech.com
 * @date 2016年4月8日
 * @version V1.0
 */
@Service
public class EduVideoServImpl implements EduVideoServ {

	private static final Logger logger = LoggerFactory.getLogger(EduModuleServImpl.class);

	@Value("#{constants['path.ffmpeg']}")
	private String ffmpegPath;

	@Value("#{constants['video.temp']}")
	private String videoTemp;

	@Autowired
	private EduVideoDao eduVideoDao;

	@Autowired
	private EduChapterVideoDao eduChapterVideoDao;

	@Override
	public Integer create(final EduVideo arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 Create 】- 开始运行 ");

		Integer index = eduVideoDao.create(arg0);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 Create 】- 完成运行 ");
		return index;
	}

	@Override
	public void update(final EduVideo arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 Update 】- 开始运行 ");

		eduVideoDao.update(arg0);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 Update 】- 完成运行 ");
	}

	@Override
	public void updateVideo(final EduVideo arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 updateVideo 】- 开始运行 ");

		eduVideoDao.updateVideo(arg0);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 updateVideo 】- 完成运行 ");
	}

	@Override
	public void updateThumb(final EduVideo arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 updateThumb 】- 开始运行 ");

		eduVideoDao.updateThumb(arg0);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 updateThumb 】- 完成运行 ");
	}

	@Override
	public void delete(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 Delete 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		eduVideoDao.delete(map);
		eduChapterVideoDao.deleteByVideoId(map);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 Delete 】- 完成运行 ");
	}

	@Override
	public Integer queryCount(final EduVideoReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = initQuery(arg0);

		Integer index = eduVideoDao.queryCount(map);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryCount 】- 完成运行 ");
		return index;
	}

	@Override
	public EduVideo queryById(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryById 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		EduVideo entity = eduVideoDao.queryById(map);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryById 】- 完成运行 ");
		return entity;
	}

	@Override
	public ListRep queryList(final Integer arg0, final EduVideoReq arg1) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryList 】- 开始运行 ");

		logger.debug(" Service req 的值为 " + arg1.toString());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		List<EduVideo> array = eduVideoDao.queryList();
		array.removeAll(queryListById(arg0));

		Iterator<EduVideo> it = array.iterator();
		while (it.hasNext()) {
			EduVideo video = it.next();
			if (null != arg1.getVideo() && !arg1.getVideo().equals("") && !video.getVideo().contains(arg1.getVideo())) {
				it.remove();
				logger.debug(" 删除的 video id 为 " + video.getId());
			}
		}

		List<EduVideoRep> list = new ArrayList<EduVideoRep>();
		int seq = arg1.getPage().getStartPage() + 1;

		for (int i = 0; i < array.size(); i++) {
			if (i >= arg1.getPage().getStartPage() && i <= arg1.getPage().getEndPage()) {
				EduVideo video = array.get(i);
				EduVideoRep videoRep = EduVideoRep.instance(video, seq);
				list.add(videoRep);
				seq++;
			}
		}

		ListRep rep = ListRep.instance(array.size(), list);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryList 】- 完成运行 ");
		return rep;
	}

	@Override
	public ListRep queryList(final EduVideoReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryList 】- 开始运行 ");

		Map<String, Object> map = initQuery(arg0);

		Integer count = eduVideoDao.queryCount(map);

		List<EduVideo> array = eduVideoDao.queryList(map);

		List<EduVideoRep> list = new ArrayList<EduVideoRep>();
		int seq = 1;

		Iterator<EduVideo> it = array.iterator();
		EduVideoRep entityRep = null;
		while (it.hasNext()) {
			EduVideo video = it.next();
			entityRep = EduVideoRep.instance(video, seq);
			list.add(entityRep);
			seq++;
		}

		ListRep rep = ListRep.instance(count, list);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryList 】- 完成运行 ");
		return rep;
	}

	@Override
	public List<EduVideo> queryListById(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryListByForExcept 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		List<EduVideo> array = eduVideoDao.queryListById(map);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryListByForExcept 】- 完成运行 ");
		return array;
	}

	@Override
	public List<EduVideo> queryListByMajorId(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryListByMajorId 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		List<EduVideo> array = eduVideoDao.queryListByMajorId(map);

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryListByMajorId 】- 完成运行 ");
		return array;
	}

	@Override
	public List<EduVideoRep> queryRepListById(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryList 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		List<EduVideoRep> array = eduVideoDao.queryRepListById(map);
		int seq = 1;

		Iterator<EduVideoRep> it = array.iterator();
		while (it.hasNext()) {
			it.next().setSeq(seq);
			seq++;
		}

		logger.debug(" 【 Serv 】- 【 EduVideoServ 】- 【 QueryList 】- 完成运行 ");
		return array;

	}

	@Override
	public UploadVideoRep upload(final MultipartFile arg0, final String arg1) throws StormrageTechException {

		logger.debug(" 【 Service 】- 【 EduVideoServ 】- 【 Upload 】- 【 STARTED 】");

		UploadVideoRep entity = null;

		String path = FileUtil.initUploadPath(arg1, "video");
		String fileName = FileUtil.saveFile(arg0, path, "video");

		fileName = FileUtil.initFileNameNoSuffix(fileName);

		entity = FileUtil.saveImageForVideo(fileName, "60", arg1, ffmpegPath, "video");

		logger.debug(" 【 Service 】- 【 EduVideoServ 】- 【 Upload 】- 【 COMPLETED 】");
		return entity;

	}

	@Override
	public UploadVideoRep upload(final String fileName, final String path) throws StormrageTechException {

		logger.debug(" 【 Service 】- 【 EduVideoServ 】- 【 Upload 】- 【 STARTED 】");

		String videoPath = FileUtil.initUploadPath(path, "video");
		String videoName = null;

		logger.debug(" fuck视频路径是 " + videoTemp + fileName);

		File ofile = new File(videoTemp + fileName);
		if (!ofile.exists() || ofile.isDirectory()) {
			throw StormrageTechException.instance(ErrCons.SERV_ERR, "文件不存在", StormrageTechException.ERR_APP,
					"【 EduVideoServ 】- 【 Upload 】");
		}

		try {

			InputStream input = new FileInputStream(ofile);
			videoName = FileUtil.saveFile(input, videoPath, fileName, "video");
			input.close();

		} catch (IOException e) {
			throw StormrageTechException.instance(ErrCons.DAO_ERR, "执行保存文件发生【 Excption 】",
					StormrageTechException.ERR_APP, "【 EduVideoServ 】-【 upload 】", e);
		}

		String nameNoSuffix = FileUtil.initFileNameNoSuffix(videoName);

		UploadVideoRep entity = FileUtil.saveImageForVideo(nameNoSuffix, "60", path, ffmpegPath, "video");

		logger.debug(" 【 Service 】- 【 EduVideoServ 】- 【 Upload 】- 【 COMPLETED 】");
		return entity;

	}

	@Override
	public void editThumb(final Integer arg0, final Integer time, final String path) throws StormrageTechException {

		logger.debug(" 【 Service 】- 【 EduVideoServ 】- 【 editThumb 】- 【 STARTED 】");

		EduVideo entity = queryById(arg0);

		String nameNoSuffix = FileUtil.initFileNameNoSuffix(entity.getUrl());

		String fileName = FileUtil.saveImageForVideo(nameNoSuffix, time, path, ffmpegPath, "video");

		entity.setThumb(fileName);

		updateThumb(entity);

		logger.debug(" 【 Service 】- 【 EduVideoServ 】- 【 editThumb 】- 【 COMPLETED 】");

	}

	private Map<String, Object> initQuery(final EduVideoReq arg0) {

		if (null == arg0)
			return null;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startPage", arg0.getPage().getStartPage());
		map.put("size", arg0.getPage().getSize());

		StringBuffer query = new StringBuffer("");

		if (null != arg0.getVideo() && arg0.getVideo().length() > 0) {
			query.append("video LIKE :video AND ");
			map.put("video", "%" + arg0.getVideo() + "%");
		}

		String sql = query.toString();
		if (null != sql && sql.length() > 0)
			map.put("query", " WHERE " + sql.substring(0, sql.length() - 4));
		else
			map.put("query", "");

		return map;
	}

}
